<template>
  <el-dialog
    v-model="showDialog"
    :title="popTitle"
    width="500px"
    :destroy-on-close="true"
  >
    <el-form
      ref="formRef"
      v-loading="loading"
      :model="formData"
      :rules="formRules"
      label-width="110px"
      class="page-form"
    >
      <el-form-item :label="t('avatar')" prop="avatar">
        <upload-image v-model="formData.avatar" />
      </el-form-item>

      <el-form-item :label="t('name')" prop="name">
        <el-input
          v-model.trim="formData.name"
          :placeholder="t('namePlaceholder')"
          clearable
          class="input-width"
        />
      </el-form-item>
      <el-form-item :label="t('work_year')" prop="work_year">
        <el-input
          v-model.trim="formData.work_year"
          :placeholder="t('work_yearPlaceholder')"
          clearable
          class="input-width"
        />
      </el-form-item>
      <el-form-item :label="t('body')" prop="body">
        <el-input
          v-model="formData.body"
          :placeholder="t('bodyPlaceholder')"
          type="textarea"
          show-word-limit
          maxlength="255"
          clearable
          class="input-width"
        />
      </el-form-item>
      <el-form-item :label="t('cert_images')" prop="cert_images">
        <upload-image v-model="formData.cert_images" :limit="5" />
      </el-form-item>
      <el-form-item :label="t('talent')" prop="talent">
        <div class="flex justify-center items-center">
          <div class="input-width mr-[15px]">
            <el-tag
              v-for="(tag, index) in formData.talent"
              :key="index"
              closable
              :disable-transitions="false"
              @close="removeTalent(tag)"
              class="mr-[10px]"
            >
              {{ tag }}
            </el-tag>
            <el-input
              v-if="inputVisible"
              ref="InputRef"
              v-model="inputValue"
              size="small"
              maxlength="10"
              :placeholder="t('talentPlaceholder')"
              @keyup.enter="saveTalent"
              @blur="saveTalent"
              class="width-short"
            />
            <el-button v-else class="width-short" size="small" @click="showInput">
              + 新增类型
            </el-button>
          </div>
        </div>
      </el-form-item>
      <el-form-item :label="t('sort')" prop="sort">
        <el-input-number
          v-model="formData.sort"
          ::step="1"
          step-strictly
          :value-on-clear="0"
          :min="0"
          class="input-width"
          :placeholder="t('sortPlaceholder')"
        />
      </el-form-item>
      <el-form-item v-if="formId != 0" :label="t('status')">
        <el-radio-group v-model="formData.status">
          <el-radio :value="1">{{ t("statusUnlock") }}</el-radio>
          <el-radio :value="0">{{ t("lock") }}</el-radio>
        </el-radio-group>
      </el-form-item>
    </el-form>

    <template #footer>
      <span class="dialog-footer">
        <el-button @click="showDialog = false">{{ t("cancel") }}</el-button>
        <el-button type="primary" :loading="loading" @click="confirm(formRef)">
          {{ t("confirm") }}
        </el-button>
      </span>
    </template>
  </el-dialog>
</template>

<script lang="ts" setup>
import { ref, reactive, computed, toRaw, nextTick } from "vue";
import { t } from "@/lang";
import type { FormInstance, InputInstance } from "element-plus";
import { addBartenderApi, editBartenderApi } from "@/app/api/alcohol";
import { deepClone } from "@/utils/common";

const showDialog = ref(false);
const loading = ref(false);
let popTitle: string = "";
const inputValue = ref("");
const inputVisible = ref(false);
const InputRef = ref<InputInstance>();

/**
 * 表单数据
 */
const formId = ref(0);
const initialFormData = {
  avatar: "",
  name: "",
  work_year: "",
  body: "",
  cert_images: "",
  talent: [],
  sort: 0,
  status: null,
};
const formData: Record<string, any> = reactive({ ...initialFormData });

const formRef = ref<FormInstance>();

// 表单验证规则
const formRules = computed(() => {
  return {
    // avatar: [{ required: true, message: t("avatarPlaceholder"), trigger: "blur" }],
    name: [{ required: true, message: t("namePlaceholder"), trigger: "blur" }],
    // work_year: [{ required: true, message: t("work_yearPlaceholder"), trigger: "blur" }],
    // body: [{ required: true, message: t("bodyPlaceholder"), trigger: "blur" }],
    // cert_images: [
    //   { required: true, message: t("cert_imagesPlaceholder"), trigger: "blur" },
    // ],
    // talent: [
    //   { type: "array", required: true, message: t("talentPlaceholder"), trigger: "blur" },
    // ],
  };
});

const emit = defineEmits(["complete"]);

// 删除调兑类型
const removeTalent = (tag: string) => {
  formData?.talent?.splice(formData?.talent?.indexOf(tag), 1);
};

// 新增调兑类型
const saveTalent = () => {
  if (inputValue.value) {
    formData?.talent?.push(inputValue.value);
  }
  inputVisible.value = false;
  inputValue.value = "";
};

const showInput = () => {
  inputVisible.value = true;
  nextTick(() => {
    InputRef.value!.input!.focus();
  });
};

/**
 * 确认
 * @param formEl
 */
const confirm = async (formEl: FormInstance | undefined) => {
  if (loading.value || !formEl) return;
  await formEl.validate(async (valid) => {
    if (valid) {
      loading.value = true;
      const data = <any>deepClone(toRaw(formData));
      data.talent = data.talent?.length ? data.talent?.join(",") : "";
      if (formId.value) {
        editBartenderApi(formId.value, data)
          .then(() => {
            showDialog.value = false;
            emit("complete");
          })
          .finally(() => {
            loading.value = false;
          });
      } else {
        addBartenderApi(data)
          .then(() => {
            showDialog.value = false;
            emit("complete");
          })
          .finally(() => {
            loading.value = false;
          });
      }
    }
  });
};

const setFormData = (row: any = null) => {
  loading.value = true;
  Object.assign(formData, initialFormData);

  if (row) {
    popTitle = t("updateBartender");
    formId.value = row.id;
    const data = <any>deepClone(row);
    Object.keys(formData).forEach((key: string) => {
      if (data[key] != undefined) formData[key] = data[key];
    });
  } else {
    popTitle = t("addBartender");
    formId.value = 0;
    formData.talent = [];
  }
  loading.value = false;
};

defineExpose({
  showDialog,
  setFormData,
});
</script>

<style lang="scss" scoped>
.width-short {
  width: 100px;
}
</style>
